/*=============================================================================

    undopath.cpp  -  Copyright (C) 1998-2005 by Don Cross

=============================================================================*/

#include "chess.h"
#include "winchess.h"
#include "winguich.h"

MoveUndoPath Global_MoveUndoPath;

MoveUndoPath::~MoveUndoPath()
{
    if ( moveList ) 
    {
        delete[] moveList;
        moveList = 0;
        current = length = size = 0;
    }
}


void MoveUndoPath::resetFromBoard ( const ChessBoard &board )
{
    int initial = board.InitialPlyNumber();
    current = length = board.GetCurrentPlyNumber() - initial;

    if ( !moveList )
    {
        size = 1024;    // arbitrary but larger than necessary
        if (size < length) {
            size = 2 * length;
        }

        moveList = new Move [size];
    }

    for (int i = 0; i < length; i++)
    {
        moveList[i] = board.GetPastMove (i + initial);
    }
}


void MoveUndoPath::undo ( ChessBoard &board )
{
    // Allow undo only if board has not been edited
    if ( board.HasBeenEdited() )
    {
        if ( Global_UI )
        {
            //TODO: Display error dialog box
        }
        return;
    }

    if ( current < 2 )
    {
        if ( Global_UI )
        {
            //TODO: Display error dialog box
        }
        return;
    }

    board.Init();
    current -= 2;
    UnmoveInfo unmove;
    for ( int i=0; i<current; i++ )
    {
        board.MakeMove ( moveList[i], unmove );
    }
}


void MoveUndoPath::redo ( ChessBoard &board )
{
    // Allow undo only if board has not been edited
    if ( board.HasBeenEdited() )
    {
        if ( Global_UI )
        {
            //TODO: Display error dialog box
        }
        return;
    }

    if ( current + 2 > length )
    {
        return;
    }

    UnmoveInfo unmove;
    board.MakeMove ( moveList[current], unmove );
    board.MakeMove ( moveList[current+1], unmove );
    current += 2;
}
